package com.demarc.pesquisas.web.converter;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import com.demarc.pesquisas.negocio.util.MascaraUtils;

@Component("MascaraConverter")
public class MascaraConverter implements Converter {
	/**
	 * {@inheritDoc}
	 */
	@Override
	public Object getAsObject(FacesContext context, UIComponent component,
			String input) {
		String object = "";

		if (StringUtils.isNotBlank(input)) {
			object = MascaraUtils.removerFormato(input);
		}
		return object;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public String getAsString(FacesContext context, UIComponent component,
			Object input) {
		String textoFormatado = "";

		String mascara = context.getApplication().evaluateExpressionGet(
				context, "#{cc.attrs.mascara}", String.class);

		if (input instanceof String && StringUtils.isNotBlank(input.toString())) {
			textoFormatado = MascaraUtils.formatar(String.valueOf(input),
					mascara);
		}
		return textoFormatado;
	}
}
